﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.SpecialUtils.Html;
using CatUtilsDll.Utils.Currency.WebUtils;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace RabbitDownload.WebSite.Pixiv
{
    internal class PixivHelper
    {
        public const string PixivOriginalImgHost = "https://i.pximg.net/img-original";

        /// <summary>
        /// 拼接图片URL的类
        /// </summary>
        /// <param name="url">图片URL</param>
        /// <param name="illust_page_count">图片数量</param>
        /// <param name="illust_id">图片ID</param>
        /// <param name="illust_ext">图片类型</param>
        /// <returns></returns>
        public Queue<String> CreateImgUrl(string url, int illust_page_count, string illust_id, string illust_ext)
        {
            Queue<String> DownLoadList = new Queue<string>();
            for (int number = 0; number < illust_page_count; number++)
            {
                String ImgIink = string.Format("{0}{1}{2}_p{3}.{4}", PixivOriginalImgHost// 原图链接指向
                          , GetImgTime(url),//匹配到的存放服务器
                        illust_id,//图片ID
                        number,
                     illust_ext);//图片类型
                Console.WriteLine(ImgIink);
                DownLoadList.Enqueue(ImgIink);
            }
            return DownLoadList;
        }

        internal string AnalysisGIF(string url, int ImgId, string ImgScore)
        {
            String SearchImg = SearchImgWithId(ImgId.ToString(), ImgScore);

            if (SearchImg != "")
                return SearchImg;
            String ImgUrl = new PixivHelper().GetImgTime(url);

            if (ImgUrl != "")
            {
                string PixivImgLink = "https://i.pximg.net/img-zip-ugoira/" + ImgUrl + ImgId + "_ugoira600x600.zip";
                new SiteSqlliteTool().InsertPixivData(ImgId.ToString(), PixivImgLink, ImgScore, "");
                return PixivImgLink;
            }
            else
                return "";
        }

        /// <summary>
        /// 通过图片ID搜索图片
        /// </summary>
        /// <param name="ImgId"></param>
        /// <returns></returns>
        private string SearchImgWithId(string ImgId, string ImgScore)
        {
            ImgId = GetImgId(ImgId).ToString();
            string ImgUrl = new SiteSqlliteTool().SelectImgLink(ImgId);
            if (ImgUrl != "")
            {
                new SiteSqlliteTool().UpDateImgScore(ImgId, ImgScore);

                return ImgUrl;
            }
            return "";
        }

        /// <summary>
        /// 获取图片的时间参数
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string GetImgTime(string url)
        {
            return TextHelper.RegexText(url, "/img/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/[0-9].*?/");
        }

        /// <summary>
        /// 初始化P站专用Header
        /// </summary>
        /// <param name="FileUrl"></param>
        /// <returns></returns>
        public WebHeaderCollection PixivHeader(String FileUrl)
        {
            WebHeaderCollection headerCollection = new WebHeaderCollection();
            headerCollection.Add("Referer", "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + GetImgId(FileUrl));
            headerCollection.Add("User-Agent", StaticValueOld.UserAgent);
            return headerCollection;
        }

        /// <summary>
        /// 规范处理json ，illust_series是特殊的分类，如果输出会导致崩溃
        /// </summary>
        /// <param name="Shtml"></param>
        /// <returns></returns>
        internal string StandartJson(string Shtml)
        {
            return TextHelper.ReplaceTextEnhance(Shtml, "\"illust_series\":{[\\w\\W]*?}", "\"illust_series\": false");
        }

        /// <summary>
        /// 获取http响应状态码的类，需要连接
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool GetStatusCode(String url)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Referer = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + Path.GetFileNameWithoutExtension(url);
            httpReq.Host = new Uri(url).Host;
            httpReq.AllowAutoRedirect = true;//这里很重要，如果你跟随和不跟随重定向得到的结果不同，由于我项目需要跟随重定向，故已经跟随。如果不需要请改为false
            httpReq.UserAgent = StaticValueOld.UserAgent;

            try
            {
                using (HttpWebResponse httpRes = (HttpWebResponse)httpReq.GetResponse())
                {
                    Console.WriteLine("返回码：" + httpRes.StatusCode);
                    if (httpRes.StatusCode == HttpStatusCode.OK)
                    {
                        Console.WriteLine(httpRes.StatusCode);

                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                ///404 403之类的错误会在这里出现
            }
            return false;
        }

        /// <summary>
        /// 检查哪一种后缀是真实的URL  请注意链接不要带.jpg后缀 直接裸文件名过来
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public static String GetImg(String ImgUrl)
        {
            if (GetStatusCode(ImgUrl + ".jpg"))
                return ImgUrl + ".jpg";
            if (GetStatusCode(ImgUrl + ".png"))
                return ImgUrl + ".png";
            return "";
        }

        /// <summary>
        /// 快速分析模式，不能解析分数，创建所有的图片URL
        /// </summary>
        /// <param name="ImgCount">图片数量</param>
        /// <param name="SingleItemUrl">图片缩略图的URL ，需要里面的时间戳</param>
        /// <param name="ImgID">图片ID</param>
        /// <returns></returns>
        public List<string> QuickAnalysisAllImg(int ImgCount, string SingleItemUrl, int ImgID, string ImgScore)
        {
            List<string> Temp = new List<string>();

            if (ImgCount == 1)
            {
                string PixivOrgLink = AnalysisSingle(SingleItemUrl, ImgID, ImgScore);
                if (PixivOrgLink != "")
                    Temp.Add(PixivOrgLink);
            }
            else if (ImgCount > 1)
            {
                if (PixivStaticValue.BlockComic)
                {
                    Console.WriteLine("选择跳出图册");
                    return Temp;
                }
                Console.WriteLine("图册情况");
                String Imgurl = AnalysisSingle(SingleItemUrl, ImgID, ImgScore);

                if (Imgurl != "")
                {
                    Console.WriteLine(Imgurl);
                    String FileExt = Path.GetExtension(Imgurl);
                    for (int i = 0; i < ImgCount; i++)
                    {
                        String illustImg = PixivOriginalImgHost +
                GetImgTime(SingleItemUrl) + ImgID + "_p" + i + FileExt;
                        Console.WriteLine("快速校对模式:" + illustImg);
                        new SiteSqlliteTool().InsertPixivData(ImgID.ToString(), illustImg, ImgScore, "");
                        Temp.Add(illustImg);
                    }
                }
            }

            return Temp;
        }

        /// <summary>
        /// 分析只有一张图的情况
        /// </summary>
        /// <param name="SingleItemUrl"></param>
        /// <param name="ImgID"></param>
        /// <param name="Temp"></param>
        private string AnalysisSingle(string SingleItemUrl, int ImgID, string ImgScore)
        {
            String SearchImg = SearchImgWithId(FileNameHelper.GetFileNameWithoutExtension(SingleItemUrl), ImgScore);
            bool UpdateImgLink = true;//判断作者是否更新了时间
            if (SearchImg != "")
            {
                UpdateImgLink = GetImgTime(SearchImg) == GetImgTime(SingleItemUrl);

                if (UpdateImgLink)
                {
                    PrintLog.INoWrite("数据库缓存：" + SearchImg);
                    return SearchImg;
                }
                else
                {
                    Console.WriteLine("时间参数有误。怀疑作者更新了文件。触发重新扫描。");
                    UpdateImgLink = false;
                }
            }
            String Imgurl = GetImg(PixivOriginalImgHost + GetImgTime(SingleItemUrl) + ImgID + "_p0");
            if (Imgurl != "")
            {
                new SiteSqlliteTool().InsertPixivData(ImgID.ToString(), Imgurl, ImgScore, "");
                if (!UpdateImgLink)
                {
                    PrintLog.ENoWrite("图片时间属性发生更改：" + UpdateImgLink);
                    new SiteSqlliteTool().UpDateImgLink(ImgID.ToString(), Imgurl, ImgScore);
                }
                return Imgurl;
            }
            else
            {
                Console.WriteLine("P站分析错误。图片ID{0}，图片链接{1}", SingleItemUrl, ImgID);
                return "";
            }
        }

        /// <summary>
        /// 缓慢分析模式，支持图片评分，因为要解析获得图片分数
        /// </summary>
        /// <param name="ImgScore"></param>
        /// <param name="ImgCount"></param>
        /// <param name="SingleItemUrl"></param>
        /// <param name="ImgID"></param>
        /// <returns></returns>
        public List<string> SlowAnalysisAllImg(int ImgScore, int ImgCount, string SingleItemUrl, int ImgID)
        {
            int score = new PixivHelper().GetScore(ImgID);
            if (score < ImgScore)
            {
                Console.WriteLine("评分低于要求，跳出！");
                return new List<string>();
            }
            return QuickAnalysisAllImg(ImgCount, SingleItemUrl, ImgID, ImgScore.ToString());
        }

        /// <summary>
        /// 获取图片ID
        /// </summary>
        /// <param name="ImgUrl"></param>
        /// <returns></returns>
        public int GetImgId(string ImgUrl)
        {
            string ImgName = FileNameHelper.GetFileNameWithoutExtension(ImgUrl);
            return TextHelper.StringToInt(TextHelper.ReplaceTextEnhance(ImgName, "_.*", ""));
        }

        /// <summary>
        /// 获取图片分数
        /// </summary>
        /// <param name="ImgId"></param>
        /// <returns></returns>
        public int GetScore(int ImgId)
        {
            int ImgScore = 0;
            String ImgPageurl = "https://www.pixiv.net/member_illust.php?mode=medium&illust_id=" + ImgId;

            String Shtml = WebHelper.HttpPcGet(ImgPageurl);

            ImgScore = TextHelper.StringToInt(
                HtmlHelper.GetFirstText(Shtml, "//ul/li[@class='info'][2]/span[@class='views']")

                );
            Console.WriteLine("解析图片ID{0}，图片分数为{1}", ImgId, ImgScore);
            return ImgScore;
        }
    }
}